package com.customview;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ViewGroup;
import androidx.constraintlayout.widget.ConstraintLayout;

public class TextViewForSpace extends androidx.appcompat.widget.AppCompatTextView {
    public TextViewForSpace(Context context) {
        this(context, null);
    }

    public TextViewForSpace(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TextViewForSpace(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            String mTextStr = getText().toString();

            //计算需要循环空格的次数
            float textPaintWidth = getPaint().measureText(mTextStr);
            int mViewWidth = ((ViewGroup) getParent()).getWidth();
            int spaceCount = (int) ((((mViewWidth - textPaintWidth) / (getText().length() - 1)) / getPaint().measureText(" ")));
            if (spaceCount < 0) {
                spaceCount = 1;
            }
            String mSpaceStr = new String(new char[spaceCount]).replace("\0", " ");

            StringBuilder mStrBuff = new StringBuilder();
            for (int i = 0; i < mTextStr.length(); i++) {
                if (i == mTextStr.length() - 1) {
                    mStrBuff.append(mTextStr.charAt(i));
                    break;
                }
                mStrBuff.append(mTextStr.charAt(i)).append(mSpaceStr);
            }
            setText(mStrBuff);
        });
    }
}
